// brandManage/pages/goodsCreate/goodsCreate.js
var app = getApp();

var common = require("../../../common/common.js").common;

var un = require("../../../siteinfo.js");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        name: "",
        alias_name: "",
        unit: "件",
        icon: [],
        carousel: [],
        only_express: 0,
        leader_only: 0,
        commission_show: 1,
        category_name: "",
        category_id: "",
        spec_typeArr: [ {
            name: "单规格",
            id: 1
        }, {
            name: "多规格",
            id: 2
        } ],
        spec_type: "单规格",
        spec_typeId: 1,
        specBox: 0,
        spec_key_value: "",
        //规格名称
        spec_key_id: "",
        //规格id
        spec_value: [],
        //规格属性
        spec_valueList: [],
        spec_items: [],
        detail: "",
        price: "",
        stock_number: 0,
        actually_sell_number: 0,
        price: "0.00",
        original_price: "0.00",
        stock_number: 0,
        prime_cost: "0.00",
        sham_sell_number: 0,
        applyBtn: true
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        let that = this;
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        that.getBase();
        if (options.id) {
            that.setData({
                id: options.id
            });
            wx.setNavigationBarTitle({
                title: "编辑"
            });
            that.getProductRead();
        } else {
            wx.setNavigationBarTitle({
                title: "添加"
            });
            that.getCategoryList();
        }
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        wx.stopPullDownRefresh();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                that.setData({
                    virtual_set_display: res.extra.virtual_set_display
                });
            }
        });
    },
    getSpecValue: function(sku_attribute) {
        let that = this;
        var spec_valueList = [];
        sku_attribute.map(x => {
            var values = [];
            x.attribute_value.map((j, k) => {
                values.push({
                    active: k == 0 ? 1 : 0,
                    id: j.id,
                    attribute_id: x.attribute_key.id,
                    value: j.value
                });
            });
            spec_valueList.push({
                key: {
                    id: x.attribute_key.id,
                    value: x.attribute_key.value
                },
                values: values
            });
        });
        console.log("spec_valueList" + JSON.stringify(spec_valueList));
        that.setData({
            spec_valueList: spec_valueList
        });
    },
    getProductRead: function() {
        let that = this;
        common.request({
            endpoint: "Lodger/lodger/product-read",
            method: "post",
            data: {
                id: that.data.id
            },
            success: res => {
                var d = res.extra;
                let icon = [];
                icon.push({
                    img_id: d.icon.id,
                    url: d.icon.img
                });
                let carousel = [];
                d.carousel.map(x => {
                    carousel.push({
                        img_id: x.id,
                        url: x.img
                    });
                });
                let sku = res.extra.sku;
                if (sku.hasOwnProperty("0,0")) {
                    //单规格
                    that.setData({
                        spec_type: "单规格",
                        spec_typeId: 1,
                        price: sku["0,0"].price,
                        prime_cost: sku["0,0"].prime_cost,
                        stock_number: sku["0,0"].stock_number,
                        original_price: sku["0,0"].o_price
                    });
                } else {
                    that.setData({
                        spec_type: "多规格",
                        spec_typeId: 2
                    });
                    var specItems = [];
                    for (var k in sku) {
                        var sku_arrtibutes = sku[k].t.replace(/,/g, "-").replace(/\|/g, ",");
                        specItems.push({
                            sku_arrtibutes: sku_arrtibutes,
                            price: sku[k].price,
                            original_price: sku[k].o_price,
                            stock_number: sku[k].stock_number,
                            prime_cost: sku[k].prime_cost
                        });
                    }
                    that.getSpecValue(res.extra.sku_attribute);
                    console.log("specItems+" + JSON.stringify(specItems));
                    that.setData({
                        specItems: specItems
                    });
                    that.getSpecData();
                }
                that.setData({
                    alias_name: d.alias_name,
                    name: d.name,
                    commission_show: d.commission_show,
                    only_express: d.only_express,
                    leader_only: d.leader_only,
                    sham_sell_number: d.sham_sell_number,
                    actually_sell_number: d.actually_sell_number,
                    carousel: carousel,
                    icon: icon,
                    category_id: d.category_id,
                    detail: d.detail
                });
                that.getCategoryList();
            }
        });
    },
    hideSpec: function() {
        let that = this;
        that.setData({
            specBox: 0
        });
    },
    showSpec: function(e) {
        let that = this;
        if (e.currentTarget.dataset.id) {
            let id = e.currentTarget.dataset.id;
            let spec_valueList = that.data.spec_valueList;
            spec_valueList.map(x => {
                if (x.key.id == id) {
                    that.setData({
                        specBox: 1,
                        spec_key_value: x.key.value,
                        spec_key_id: x.key.id,
                        spec_value: x.values
                    });
                }
            });
        } else {
            that.setData({
                specBox: 1,
                spec_key_value: "",
                spec_key_id: "",
                spec_value: []
            });
        }
    },
    saveSpec: function(e) {
        let that = this;
        let spec_value = that.data.spec_value;
        let i = e.currentTarget.dataset.index;
        spec_value[i].value = e.detail.value;
        that.setData({
            spec_value: spec_value
        });
    },
    chooseSpec: function(e) {
        let that = this;
        let spec_valueList = that.data.spec_valueList;
        var attribute_id = e.currentTarget.dataset.attributeid;
        var id = e.currentTarget.dataset.id;
        spec_valueList.map(x => {
            if (x.key.id == attribute_id) {
                x.values.map(m => {
                    if (m.id == id) {
                        m.active = 1;
                    } else {
                        m.active = 0;
                    }
                });
            }
        });
        that.setData({
            spec_valueList: spec_valueList
        });
        that.getSpecData();
    },
    addSpec: function() {
        let that = this;
        let spec_value = that.data.spec_value;
        if (spec_value.length >= 10) {
            wx.showModal({
                title: "提示",
                content: "规格属性只能添加10个",
                showCancel: false
            });
            return false;
        }
        spec_value.push({
            value: ""
        });
        that.setData({
            spec_value: spec_value
        });
    },
    specDel: function(e) {
        let that = this;
        if (!that.data.spec_key_id) {
            that.setData({
                specBox: 0
            });
        }
        common.request({
            endpoint: "Lodger/lodger/spec-del",
            method: "post",
            data: {
                id: that.data.spec_key_id,
                method: 1
            },
            success: res => {
                let spec_valueList = that.data.spec_valueList;
                spec_valueList.map((x, i) => {
                    if (x.key.id == that.data.spec_key_id) {
                        spec_valueList.splice(i, 1);
                    }
                });
                that.setData({
                    spec_valueList: spec_valueList,
                    specBox: 0
                });
                that.getSpecItems();
            }
        });
    },
    specCreate: common.throttle(function() {
        let that = this;
        if (!that.data.spec_key_value || !that.data.spec_value.length) {
            wx.showModal({
                title: "提示",
                content: "请完善规格名称和规格属性",
                showCancel: false
            });
            return false;
        }
        for (var j = 0; j < that.data.spec_value.length; j++) {
            if (!that.data.spec_value[j].value) {
                wx.showModal({
                    title: "提示",
                    content: "规格属性填写不完整",
                    showCancel: false
                });
                return false;
            }
        }
        var param = {
            key: {
                value: that.data.spec_key_value
            },
            values: that.data.spec_value
        };
        if (that.data.spec_key_id) {
            param.key.id = that.data.spec_key_id;
        }
        common.request({
            endpoint: "Lodger/lodger/spec-create",
            method: "post",
            data: param,
            success: res => {
                var spec_valueList = that.data.spec_valueList;
                var d = res.extra;
                d.values[0].active = 1;
                if (that.data.spec_key_id) {
                    spec_valueList.map((x, i) => {
                        if (x.key.id == d.key.id) {
                            spec_valueList[i] = d;
                        }
                    });
                } else {
                    spec_valueList.push(res.extra);
                }
                that.setData({
                    spec_valueList: spec_valueList
                });
                that.getSpecItems();
            },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: err.message,
                    showCancel: false
                });
            }
        });
    }, 3e3),
    getSpecItems: function() {
        //优化
        let that = this;
        let spec_valueList = that.data.spec_valueList;
        let specItems = [];
        var len = spec_valueList.length;
        var data1 = spec_valueList[len - 1];
        if (len - 1 > 0) {
            //大于1级
            let data2 = spec_valueList[len - 2];
            if (len - 2 > 0) {
                //大于二级，三级
                let data3 = spec_valueList[len - 3];
                data1.values.map(k => {
                    data2.values.map(m => {
                        data3.values.map(n => {
                            specItems.push({
                                sku_arrtibutes: data1.key.id + "-" + k.id + "," + data2.key.id + "-" + m.id + "," + data3.key.id + "-" + n.id,
                                price: "0",
                                original_price: "0",
                                stock_number: 0,
                                prime_cost: "0"
                            });
                        });
                    });
                });
            } else {
                //二级
                data1.values.map(k => {
                    data2.values.map(m => {
                        specItems.push({
                            sku_arrtibutes: data1.key.id + "-" + k.id + "," + data2.key.id + "-" + m.id,
                            price: "0",
                            original_price: "0",
                            stock_number: 0,
                            prime_cost: "0"
                        });
                    });
                });
            }
        } else {
            //1级
            data1.values.map(k => {
                specItems.push({
                    sku_arrtibutes: data1.key.id + "-" + k.id,
                    price: "0",
                    original_price: "0",
                    stock_number: 0,
                    prime_cost: "0"
                });
            });
        }
        that.setData({
            specItems: specItems,
            specBox: 0
        });
        console.log(spec_valueList);
        console.log(specItems);
        that.getSpecData();
    },
    getSpecData: function() {
        let that = this;
        let specItems = that.data.specItems;
        let spec_valueList = that.data.spec_valueList;
        let currentSpecCopy = [];
        spec_valueList.map(x => {
            x.values.map(n => {
                if (n.active == 1) {
                    currentSpecCopy.push(n.attribute_id + "-" + n.id);
                }
            });
        });
        let currentSpec = [];
        currentSpec[0] = currentSpecCopy.join(",");
        console.log("currentSpec" + currentSpec);
        specItems.map(x => {
            var sku_arrtibutes = [];
            sku_arrtibutes[0] = x.sku_arrtibutes;
            if (that.scalarArrayEquals(sku_arrtibutes, currentSpec)) {
                that.setData({
                    currentSpec: currentSpec,
                    price: x.price,
                    original_price: x.original_price,
                    prime_cost: x.prime_cost,
                    stock_number: x.stock_number
                });
            }
        });
    },
    scalarArrayEquals(array1, array2) {
        array1 = array1[0].split(",");
        array2 = array2[0].split(",");
        return array1.length == array2.length && array1.every(function(v, i) {
            var back = 0;
            array2.map((k, j) => {
                if (k == v) {
                    back = 1;
                }
            });
            return back == 1 ? true : false;
        });
    },
    delSpec: function(e) {
        let that = this;
        let spec_value = that.data.spec_value;
        let i = e.currentTarget.dataset.index;
        spec_value.splice(i, 1);
        that.setData({
            spec_value: spec_value
        });
    },
    saveWord: function(e) {
        let that = this;
        var key = e.currentTarget.dataset.name;
        that.setData({
            [key]: e.detail.value
        });
    },
    saveWordItem: function(e) {
        let that = this;
        var key = e.currentTarget.dataset.name;
        that.setData({
            [key]: e.detail.value
        });
        if (that.data.spec_typeId == 2) {
            let specItems = that.data.specItems;
            let currentSpec = that.data.currentSpec;
            specItems.map(x => {
                var sku_arrtibutes = [];
                sku_arrtibutes[0] = x.sku_arrtibutes;
                if (that.scalarArrayEquals(sku_arrtibutes, currentSpec)) {
                    console.log("key" + key);
                    for (var k in x) {
                        if (k == key) {
                            x[key] = e.detail.value;
                        }
                    }
                }
            });
            console.log("specItems" + JSON.stringify(specItems));
            that.setData({
                specItems: specItems
            });
        }
    },
    switchChange: function(e) {
        let that = this;
        var key = e.currentTarget.dataset.name;
        console.log("radio" + e.detail.value);
        that.setData({
            [key]: e.detail.value ? 1 : 0
        });
    },
    bindCateChange: function(e) {
        let that = this;
        that.setData({
            category_name: that.data.categoryList[e.detail.value].name,
            category_id: that.data.categoryList[e.detail.value].id
        });
    },
    bindSpecChange: function(e) {
        let that = this;
        that.setData({
            spec_type: that.data.spec_typeArr[e.detail.value].name,
            spec_typeId: that.data.spec_typeArr[e.detail.value].id
        });
        if (that.data.spec_typeId == 1) {
            that.setData({
                spec_valueList: []
            });
        }
    },
    //上传图片
    uploadImage: function(e) {
        var that = this;
        let icon = that.data.icon;
        let carousel = that.data.carousel;
        let domian = app.globalData.domain;
        let count;
        if (e.currentTarget.dataset.name == "icon") {
            let len = that.data.icon.length;
            count = 1 - len;
        } else if (e.currentTarget.dataset.name == "carousel") {
            let len = that.data.carousel.length;
            count = 6 - len;
        }
        let uniacid;
        if (wx.getStorageSync("uniacid")) {
            uniacid = wx.getStorageSync("uniacid");
        } else {
            uniacid = un.uniacid;
        }
        wx.chooseImage({
            count: count,
            //最多可以选择的图片总数
            sizeType: [ "compressed" ],
            // 可以指定是原图还是压缩图，默认二者都有
            sourceType: [ "album", "camera" ],
            // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                var tempFilePaths = res.tempFilePaths;
                //启动上传等待中...
                                wx.showLoading({
                    title: "正在上传..."
                });
                var i = 0;
                var length = tempFilePaths.length;
                var upload = function() {
                    wx.uploadFile({
                        url: domian + "Lodger/lodger/product-img-upload",
                        filePath: tempFilePaths[i],
                        name: "file",
                        formData: {},
                        header: {
                            "Content-Type": "multipart/form-data",
                            uniacid: uniacid
                        },
                        success: function(res) {
                            var data = JSON.parse(res.data);
                            if (e.currentTarget.dataset.name == "icon") {
                                icon.push(data.extra);
                            } else if (e.currentTarget.dataset.name == "carousel") {
                                carousel.push(data.extra);
                            }
                            i++;
                            if (i < length) {
                                upload();
                            } else {
                                wx.hideLoading();
                                if (e.currentTarget.dataset.name == "icon") {
                                    that.setData({
                                        icon: icon
                                    });
                                    console.log("icon" + JSON.stringify(icon));
                                } else if (e.currentTarget.dataset.name == "carousel") {
                                    that.setData({
                                        carousel: carousel
                                    });
                                    console.log("carousel" + JSON.stringify(carousel));
                                }
                            }
                        },
                        fail: function(res) {
                            wx.hideToast();
                            wx.showModal({
                                title: "错误提示",
                                content: "上传图片失败",
                                showCancel: false,
                                success: function(res) {}
                            });
                        }
                    });
                };
                upload();
            }
        });
    },
    //删除图片
    delete_img: function(e) {
        let that = this;
        let index = e.currentTarget.dataset.index;
        let icon = that.data.icon;
        let carousel = that.data.carousel;
        if (e.currentTarget.dataset.name == "icon") {
            icon.splice(index, 1);
            that.setData({
                icon: icon
            });
        } else if (e.currentTarget.dataset.name == "carousel") {
            carousel.splice(index, 1);
            that.setData({
                carousel: carousel
            });
        }
    },
    getCategoryList: function() {
        var that = this;
        common.request({
            endpoint: "Lodger/lodger/product-category",
            method: "post",
            data: {},
            success: res => {
                let categoryList = [];
                if (res.extra.length) {
                    res.extra.filter(x => {
                        if (x.sub.length) {
                            x.sub.filter(j => {
                                categoryList.push({
                                    name: j.name,
                                    id: j.id
                                });
                                if (that.data.category_id && that.data.category_id == j.id) {
                                    that.setData({
                                        category_name: j.name
                                    });
                                }
                            });
                        }
                    });
                }
                that.setData({
                    categoryList: categoryList
                });
            }
        });
    },
    createPro: common.throttle(function() {
        let that = this;
        if (!that.data.applyBtn) {
            return false;
        }
        that.setData({
            applyBtn: false
        });
        if (!that.data.name) {
            wx.showModal({
                title: "提示",
                content: "请输入商品名称",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            applyBtn: true
                        });
                    }
                }
            });
            return false;
        }
        if (!that.data.alias_name) {
            wx.showModal({
                title: "提示",
                content: "请输入商品名称短标题",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            applyBtn: true
                        });
                    }
                }
            });
            return false;
        }
        if (!that.data.icon.length || !that.data.carousel.length) {
            wx.showModal({
                title: "提示",
                content: "请上传商品缩略图和主图",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            applyBtn: true
                        });
                    }
                }
            });
            return false;
        }
        if (!that.data.category_id) {
            wx.showModal({
                title: "提示",
                content: "请选择商品分类",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            applyBtn: true
                        });
                    }
                }
            });
            return false;
        }
        let icon = that.data.icon;
        var iconId = [];
        icon.filter(x => {
            iconId.push(x.img_id);
        });
        let carousel = that.data.carousel;
        var carouselId = [];
        carousel.filter(x => {
            carouselId.push(x.img_id);
        });
        var params = {
            name: that.data.name,
            alias_name: that.data.alias_name,
            unit: that.data.unit,
            icon: iconId.join(","),
            carousel: carouselId.join(","),
            only_express: that.data.only_express,
            leader_only: that.data.leader_only,
            commission_show: that.data.commission_show,
            category_id: that.data.category_id,
            detail: that.data.detail,
            sham_sell_number: that.data.sham_sell_number
        };
        console.log(params);
        if (that.data.spec_typeId == 1) {
            params["items"] = [ {
                sku_arrtibutes: "0-0",
                price: that.data.price,
                original_price: that.data.original_price,
                stock_number: that.data.stock_number,
                prime_cost: that.data.prime_cost
            } ];
        } else {
            params["items"] = that.data.specItems;
        }
        if (that.data.id) {
            params["id"] = that.data.id;
        }
        common.request({
            endpoint: "Lodger/lodger/product-add",
            method: "post",
            data: params,
            success: res => {
                var editText;
                if (that.data.id) {
                    editText = "编辑";
                } else {
                    editText = "创建";
                }
                wx.showToast({
                    title: editText + "成功"
                });
                that.setData({
                    applyBtn: true
                });
                setTimeout(() => {
                    wx.navigateBack({});
                }, 1e3);
            },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: err.mes,
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            that.setData({
                                applyBtn: true
                            });
                        }
                    }
                });
            }
        });
    }, 3e3),
    goToGoodsDetail: function() {
        wx.navigateTo({
            url: "/brandManage/pages/goodsDetail/goodsDetail"
        });
    }
});